/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.servicequery;

import han.bashe.common.bifang.BifangClient;
import han.bashe.common.cache.InnerCache;
import han.bashe.common.config.Config;
import han.bashe.common.exception.BasheException;
import han.bashe.common.schema.MappingServiceInfoWrapper;
import han.bashe.common.schema.ServiceInfoWrapper;
import v1.query.web.bifang.han.QueryResponseDocument.QueryResponse;
import v1.query.web.bifang.han.ServiceBusDocument.ServiceBus;

/**
 * @Author Kent
 */
public class CacheWrapper {
	
	public static Object getService(String code)throws BasheException{
		if(Config.cacheEnable){
			Object ret = InnerCache.getService(code);
			if(ret == null){
				ret = InnerCache.getMappingService(code);
			}
			if(ret == null){
				QueryResponse res = BifangClient.getServiceInfo(code);
				if(res.getResult().getService() != null){
					ret = new ServiceInfoWrapper(res.getResult().getService() );
					InnerCache.putService(res.getResult().getService());
				}else{
					ret = new MappingServiceInfoWrapper(res.getResult().getMappingService());
					InnerCache.putMappingService(res.getResult().getMappingService());
				}
			}
			return ret;
		}else{
			Object ret = null;
			QueryResponse res = BifangClient.getServiceInfo(code);
			if(res.getResult().getService() != null){
				ret = new ServiceInfoWrapper(res.getResult().getService() );
				
			}else{
				ret = new MappingServiceInfoWrapper(res.getResult().getMappingService());
				
			}
			return ret;
		}
	}
	
	public static boolean getAccessResult(String user,String password, String service)throws BasheException{
		if(Config.cacheEnable){
			Boolean result = InnerCache.gutAccessResult(user, password, service);
			if(result == null){
				result = new Boolean(BifangClient.canAccess(user, password, service));
				InnerCache.putAccessResult(user, password, service, result);
			}
			return result;
		}else{
			return BifangClient.canAccess(user, password, service);
		}
	}
	
	public static ServiceBus getServiceBus(String id)throws BasheException{
		if(Config.cacheEnable){
			ServiceBus bus =  InnerCache.getServiceBus(id);
			if(bus == null){
				bus = BifangClient.getServiceBusInfoById(id);
				InnerCache.putServiceBus(bus);
			}
			return bus;
		}else{
			return BifangClient.getServiceBusInfoById(id);
		}
	}

}
